<template>
	<div class="background">
		<div class="login" v-show="!resetDialogVisible">
			<el-form ref="formRef" :model="ruleForm" :rules="rules" label-width="auto" class="demo-ruleForm"
				:size="formSize" status-icon>
				<div class="title">教务系统</div>

				<el-form-item label="账号" prop="acc">
					<el-input v-model="ruleForm.acc" placeholder="请输入账号" :prefix-icon="User" />
				</el-form-item>

				<el-form-item label="密码" prop="pwd">
					<el-input type="password" v-model="ruleForm.pwd" placeholder="请输入密码" :prefix-icon="Key"
						show-password />
				</el-form-item>

				<div class="code">
					<el-form-item label="验证码" prop="code" style="display: flex; align-items: center;">
						<el-input v-model="ruleForm.code" placeholder="验证码" style="width: 80px;" />
						<span class="code-image" @click="refreshCaptcha"></span>
					</el-form-item>
				</div>

				<el-form-item>
					<el-button type="primary" @click="submitForm()" class="button">
						登录
					</el-button>
				</el-form-item>


			</el-form>
			<div class="forgot-password">
				<el-link type="primary" @click="showResetDialog">忘记密码？</el-link>
			</div>
		</div>

		<!-- 忘记密码对话框 -->
		<el-dialog v-model="resetDialogVisible" title="重置密码" width="420px" @close="handleDialogClose">
			<el-form class="forgot-pwd" :model="passwordResetForm" :rules="resetRules" ref="resetFormRef"
				label-width="80px">
				<el-form-item label="账号" prop="account">
					<el-input v-model="passwordResetForm.account" placeholder="请输入账号"></el-input>
				</el-form-item>
				<el-form-item label="邮箱" prop="email">
					<el-input v-model="passwordResetForm.email" placeholder="请输入绑定的邮箱"></el-input>
				</el-form-item>
				<el-form-item label="验证码" prop="code" style="display: flex; align-items: center;">
					<el-input v-model="passwordResetForm.code" placeholder="验证码" style="width: 80px;" />
					<span class="code-image" @click="refreshResetCaptcha"></span>
				</el-form-item>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="handleDialogClose">取消</el-button>
					<el-button type="primary" @click="handleResetPassword">请求重置密码</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script setup>
	import {
		ref,
		onMounted
	} from 'vue';
	import {
		useRouter
	} from 'vue-router';
	import {
		ElMessage
	} from 'element-plus';
	import {
		User,
		Key
	} from '@element-plus/icons-vue';
	import {login, getCode, forgotPassword} from '@/api/user'

	const router = useRouter();
	const formRef = ref();

	// 生成一个唯一的key
	const generateKey = () => {
		return Math.random().toString(36).substr(2, 15) + Math.random().toString(36).substr(2, 15);
	}

	const ruleForm = ref({
		acc: '',
		pwd: '',
		code: '',
		key: generateKey()
	});

	const rules = {
		acc: [{
				required: true,
				message: '请输入账号',
				trigger: 'blur'
			},
			{
				min: 4,
				message: '长度在 4 以上个字符',
				trigger: 'blur'
			}
		],
		pwd: [{
				required: true,
				message: '请输入密码',
				trigger: 'blur'
			},
			{
				min: 6,
				message: '长度在 6 到 20 个字符',
				trigger: 'blur'
			}
		],
		code: [{
			required: true,
			message: '请输入验证码',
			trigger: 'blur'
		}]
	};

	// 刷新验证码
	const refreshCaptcha = () => {
		const key = generateKey();
		ruleForm.value.key = key;
		
		getCode(key).then(response => {
			const codeBase64 = response.data.codeBase64;
			const captchaImage = document.querySelector('.code-image');
			if (captchaImage) {
				captchaImage.style.backgroundImage = `url(data:image/png;base64,${codeBase64})`;
				captchaImage.style.backgroundSize = 'cover';
			}
		}).catch(error => {
			ElMessage.error('获取验证码失败');
		});
	}

	// 登录按钮
	const submitForm = async () => {
		try {
			// 验证表单
			await formRef.value.validate();
			
			const res = await login({
				userAcc: ruleForm.value.acc,
				userPwd: ruleForm.value.pwd,
				key: ruleForm.value.key,
				code: ruleForm.value.code
			});
			console.log(res);			
			if (res.code === 400) {
				ElMessage.error(res.message || '验证码错误');
				refreshCaptcha();
			} else if (res.code === 401) {
				ElMessage.error(res.message || '账号或密码错误');
				refreshCaptcha();
			} else {
        console.log(res.data);
				ElMessage.success(res.message || '登录成功');
				//存入浏览器内存
				//现在保存token..
				localStorage.setItem('token', res.data.token);
        sessionStorage.setItem('campusId', res.data.user.campusId);
        sessionStorage.setItem('user', JSON.stringify(res.data.user) )
				router.push('/main');
			}
		} catch (error) {
			if (error.name !== 'AxiosError') {
				ElMessage.error('表单验证失败');
			}
		}
	};

	const resetForm = () => {
		ruleForm.value.acc = '';
		ruleForm.value.pwd = '';
		ruleForm.value.key = '';
		ruleForm.value.code = '';
	};

	// 组件挂载时获取验证码
	onMounted(() => {
		refreshCaptcha();
	});

	// 忘记密码相关
	const resetDialogVisible = ref(false);
	const resetFormRef = ref();
	const passwordResetForm = ref({
		account: '',
		email: '',
		code: '',
		key: generateKey()
	});

	const resetRules = {
		account: [{
				required: true,
				message: '请输入账号',
				trigger: 'blur'
			},
			{
				min: 4,
				message: '长度在 4 个字符以上',
				trigger: 'blur'
			}
		],
		email: [{
				required: true,
				message: '请输入邮箱',
				trigger: 'blur'
			},
			{
				type: 'email',
				message: '请输入正确的邮箱格式',
				trigger: 'blur'
			}
		],
		code: [{
			required: true,
			message: '请输入验证码',
			trigger: 'blur'
		}]
	};

	// 刷新重置密码验证码
	const refreshResetCaptcha = () => {
		const key = generateKey();
		passwordResetForm.value.key = key;

		getCode(key).then(response => {
			const codeBase64 = response.data.codeBase64;
			const captchaImage = document.querySelector('.el-dialog .code-image');
			if (captchaImage) {
				captchaImage.style.backgroundImage = `url(data:image/png;base64,${codeBase64})`;
				captchaImage.style.backgroundSize = 'cover';
			}
		}).catch(error => {
			ElMessage.error('获取验证码失败');
		});
	};

	// 处理对话框关闭
	const handleDialogClose = () => {
		resetDialogVisible.value = false;
		// 刷新登录窗口的验证码
		refreshCaptcha();
	};

	//展示忘记密码窗口
	const showResetDialog = () => {
		resetDialogVisible.value = true;
		passwordResetForm.value = {
			account: '',
			email: '',
			code: '',
			key: generateKey()
		};
		// 打开对话框时获取验证码
		setTimeout(() => {
			refreshResetCaptcha();
		}, 100);
	};

	const handleResetPassword = async () => {
		try {
			await resetFormRef.value.validate();

			const res = await forgotPassword({
				userAcc: passwordResetForm.value.account,
				userEmail: passwordResetForm.value.email,
				key: passwordResetForm.value.key,
				code: passwordResetForm.value.code
			});

			if (res.code === 400) {
				ElMessage.error(res.message || '验证码错误');
				refreshResetCaptcha();
			} else if (res.code === 401) {
				ElMessage.error(res.message || '账号或邮箱不匹配');
				refreshResetCaptcha();
			} else {
				ElMessage.success('重置密码请求已发送，请查收邮件，获取密码信息');
				resetDialogVisible.value = false;
			}
		} catch (error) {
			if (error.name !== 'AxiosError') {
				ElMessage.error('表单验证失败');
			}
		}
	};
</script>

<style scoped>
	.background {
		width: 100vw;
		height: 100vh;
		background-image: url("../img/bg.png");
		background-size: cover;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.title {
		width: 100%;
		height: 80px;
		line-height: 60px;
		text-align: center;
		font-size: 26px;
	}

	.login {
		width: 420px;
		height: 350px;
		background-color: rgba(255, 255, 255, 0.822);
		border-radius: 8px;
		box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
	}

	.demo-ruleForm {
		width: 325px;
		height: 300px;
		margin: auto;
		padding: 20px;
	}

	.code-image {
		width: 130px;
		height: 40px;
		background-color: #f0f0f0;
		cursor: pointer;
		margin-left: 10px;
		display: inline-block;
		vertical-align: middle;
		border-radius: 4px;
		border: 1px solid #dcdfe6;
	}

	.button {
		width: 100%;
		margin-left: 0px;
		margin-top: 20px;
	}

	.forgot-password {
		margin-top: 15px;
		text-align: right;
	}

	.dialog-footer {
		display: flex;
		justify-content: flex-end;
		gap: 10px;
	}

	.forgot-pwd {
		width: 325px;
		margin-left: 20px;
	}
</style>